//
//  DynamicImageViewController.m
//  夜间模式（系统）
//
//  Created by aaaa on 2020/5/27.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "DynamicImageViewController.h"

@interface DynamicImageViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (weak, nonatomic) IBOutlet UIImageView *img2;

@end

@implementation DynamicImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.systemBackgroundColor;
    _imgView.image = [UIImage imageNamed:@"apple"];
    _img2.image = [UIImage imageNamed:@"strawberry"];
}

-(void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
    if (UITraitCollection.currentTraitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
        _img2.image = [self greyImageWithImage:[UIImage imageNamed:@"strawberry"]];
    }else{
        _img2.image = [UIImage imageNamed:@"strawberry"];
    }
}

- (UIImage*)greyImageWithImage:(UIImage*)image
{
    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize resultSize = CGSizeMake(image.size.width*scale, image.size.height*scale);
    
    CGRect imageRect = CGRectMake(0, 0, resultSize.width, resultSize.height);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate(nil, resultSize.width, resultSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(context, imageRect, [image CGImage]);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);
    return newImage;
}

@end
